<script src="{{ cdn_prev }}jquery@3.7.0/dist/jquery.min.js"></script>
<script src="{{ cdn_prev }}notyf@3.10.0/notyf.min.js"></script>

<script src="{{ cdn_prev }}@creative-tim-official/argon-dashboard@2.0.4/assets/js/core/popper.min.js"></script>
<script src="{{ cdn_prev }}bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js"></script>
<script src="{{ cdn_prev }}@creative-tim-official/argon-dashboard@2.0.4/assets/js/plugins/perfect-scrollbar.min.js"></script>
<script src="{{ cdn_prev }}@creative-tim-official/argon-dashboard@2.0.4/assets/js/plugins/smooth-scrollbar.min.js"></script>
<script src="{{ cdn_prev }}@creative-tim-official/argon-dashboard@2.0.4/assets/js/plugins/chartjs.min.js"></script>
<script src="{{ cdn_prev }}qexo-static@2.2.3/qexo/argon/argon-dashboard.js"></script>
<script src="{{ cdn_prev }}github-buttons@2.27.0/dist/buttons.min.js"></script>
<script>
    $.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}'}});

    var notyf = new Notyf({position: {x: 'right', y: 'top'}});

    var notifications = [];

    function KZ_Loading(config) {
        if (this instanceof KZ_Loading) {
            const domTemplate = `
            <div class="modal fade" id="loaderModal-@@KZ_Loadin_ID@@" tabindex="-1" aria-labelledby="loaderModalLabel-@@KZ_Loadin_ID@@"
                 aria-hidden="true" data-bs-keyboard="false" data-bs-backdrop="static">
                <div class="modal-dialog">
                </div>
                    <div style="width: 200px;height:20px; z-index: 20000; position: absolute; text-align: center; left: 50%; top: 50%;margin-left:-100px;margin-top:-10px">
                        <div class="progress progress-striped active" style="margin-bottom: 0;">
                            <div class="progress-bar" style="width: 100%;"></div>
                        </div>
                        <h5 style="font-size: .8125rem;margin-bottom: .5rem;font-family: inherit;font-weight: 600;line-height: 1.5;color: #32325d;">@@KZ_Loading_Text@@</h5>
                    </div>
            </div>`
            this.config = {
                content: '正在加载中...',
                time: 0,
            };
            if (config != null) {
                if (typeof config === 'string') {
                    this.config = Object.assign(this.config, {
                        content: config
                    });
                } else if (typeof config === 'object') {
                    this.config = Object.assign(this.config, config);
                }
            }
            this.id = new Date().getTime().toString();
            this.state = 'hide';

            /*显示 */
            this.show = function () {
                $('#loaderModal-' + this.id).modal("show");
                this.state = 'show';
                if (this.config.time > 0) {
                    var that = this;
                    setTimeout(function () {
                        that.hide();
                    }, this.config.time);
                }
            };
            /*隐藏 */
            this.hide = function (callback) {
                $('#loaderModal-' + this.id).modal("hide");
                this.state = 'hide';
                if (callback) {
                    callback();
                }
            };
            /*销毁dom */
            this.destroy = function () {
                var that = this;
                this.hide();
                setTimeout(function () {
                    that.hide(function () {
                        var node = $('#loaderModal-' + that.id);
                        node.next().remove();
                        node.remove();
                        that.show = function () {
                            throw new Error('对象已销毁！');
                        };
                        that.hide = function () {
                        };
                        that.destroy = function () {
                        };
                    });
                }, 300);
            }

            var domHtml = domTemplate.replaceAll('@@KZ_Loadin_ID@@', this.id).replaceAll('@@KZ_Loading_Text@@', this.config.content);
            $('body').append(domHtml);
        } else {
            return new KZ_Loading(config);
        }
    }

    var notificationTemp = `<a class="dropdown-item border-radius-md" href="@@herf@@" style="white-space: inherit;">
                                <div class="d-flex py-1">
                                    <div class="avatar avatar-sm me-3 my-auto" style="color: #172b4d;">
                                      @@fore@@
                                    </div>
                                    <div class="d-flex flex-column justify-content-center">
                                        <span class="text-sm font-weight-normal mb-1">
                                        <span class="font-weight-bold">@@label@@</span><br>
                                            @@content@@
                                        </span>
                                        <p class="text-xs text-secondary mb-0">
                                            <i class="fa fa-clock me-1"></i>
                                            @@time@@
                                        </p>
                                    </div>
                                </div>
                            </a>`

    function showNotifications() {
        if (!notifications.length) {
            $("#notification-board").html(notificationTemp.replace('<span class="font-weight-bold">@@lebel@@<br></span><br>', '').replace("@@herf@@", "#")
                .replace('@@content@@', '你当前没有消息哟~').replace('@@time@@', 'Now').replace('@@fore@@',
                    '<i class="fas fa-check"></i>').replace("@@label@@", "提示"));
            $("#msg-point").css({"background": "inherit"});
        } else {
            let html = '<div class="px-3 py-1"><h6 class="text-sm text-muted m-0">你有 ' +
                '<strong class="text-primary">' + notifications.length + '</strong> 则消息' +
                '</h6></div><div class="list-group list-group-flush">';
            for (let i = 0; i < notifications.length; i++) {
                html += notificationTemp.replace('@@herf@@', "javascript:delNotification('"
                    + notifications[i]["timestamp"] + "')")
                    .replace('@@content@@', notifications[i]["content"])
                    .replace('@@time@@', notifications[i]["time"])
                    .replace('@@fore@@', `<i class="fas fa-quote-left"></i>`)
                    .replace("@@label@@", notifications[i]["label"]);
            }
            html += '<div class="px-3 py-1"><h6 class="text-sm text-primary m-0" ' +
                'style="cursor: pointer;text-align: right;" onclick="clearNotification()">清除全部' +
                '</h6></div>'
            $("#notification-board").html(html + '</div>');
            $("#msg-point").css({
                "position": "absolute", "margin-top": "-25px", "margin-left": "15px", "width":
                    "6px", "height": "6px", "background": "red", "border-radius": "50%"
            });
        }
    }

    $.ajax({
        url: "/api/get_notifications/",
        type: "get",
        success: function (res) {
            let data = res;
            if (data["status"]) {
                notifications = data["data"];
                showNotifications();
            } else {
                $("#notification-board").html(notificationTemp.replace('@@lebel@@', '提示')
                    .replace("@@herf@@", "#").replace('@@content@@', '消息加载失败咯').replace
                    ('@@time@@', 'Error')
                    .replace('@@fore@@', '<i class="fa-solid fa-blender"></i>'));
            }
        }
    })

    function delNotification(timestamp) {
        $.ajax({
            url: "/api/del_notifications/",
            type: "post",
            dataType: "JSON",
            data: {"time": timestamp},
            success: function (res) {
                if (res.status) {
                    notyf.success(res.msg);
                    for (let i = 0; i < notifications.length; i++) {
                        if (notifications[i]["timestamp"] === timestamp) {
                            notifications.splice(i, 1);
                            break;
                        }
                    }
                    showNotifications();
                } else {
                    notyf.error(res.msg);
                }
            },
            error: function (res) {
                notyf.error("网络错误!");
            }
        })
    }

    function clearNotification() {
        $.ajax({
            url: "/api/clear_notifications/",
            type: "post",
            dataType: "JSON",
            success: function (res) {
                if (res.status) {
                    notyf.success(res.msg);
                    notifications = [];
                    showNotifications();
                } else {
                    notyf.error(res.msg);
                }
            },
            error: function (res) {
                notyf.error("网络错误!");
            }
        })
    }

    function escapeString(str) {
        var temp = "";
        str = str.toString();
        if (str.length === 0) return "";
        temp = str.replace(/&/g, "&amp;");
        temp = temp.replace(/</g, "&lt;");
        temp = temp.replace(/>/g, "&gt;");
        temp = temp.replace(/\s/g, "&nbsp;");
        temp = temp.replace(/\'/g, "&#39;");
        temp = temp.replace(/\"/g, "&quot;");
        return temp
    }

    function getRFC3339() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        var millisecond = date.getMilliseconds();
        var offset = date.getTimezoneOffset();
        var offsetHour = Math.floor(Math.abs(offset / 60));
        var offsetMinute = Math.abs(offset % 60);
        var offsetSign = offset < 0 ? "+" : "-";
        return year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second + "." + millisecond + offsetSign + offsetHour + ":" + offsetMinute;
    }


    function sleepSync(ms) {
        const endTime = Date.now() + ms;
        while (1) {
            if (Date.now() > endTime) {
                return;
            }
        }
    }


    function trimSpace(array) {
        for (let i = 0; i < array.length; i++) {
            if (array[i] == null || typeof (array[i]) == "undefined") {
                array.splice(i, 1);
                i = i - 1;
            }
        }
        return array;
    }

    function scrollToTop() {
        document.body.scrollIntoView();
    }

    function checkIfDark() {
        let classList = $("body").attr("class");
        if (classList.indexOf("dark-version") !== -1) {
            return true;
        }
        return false;
    }

    {% if error %}
        notyf.error("{{ error }}");
    {% endif %}
</script>